package com.lsh.service.Impl;

import com.lsh.model.Admin;
import com.lsh.repository.AdminRepository;
import com.lsh.service.AdminService;
import com.lsh.util.IdWorker;
import com.lsh.util.JwtUtil;
import com.lsh.util.ResultObject;
import com.lsh.util.StatusCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.MalformedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/11/3 1:43 下午
 * @desc ：
 */
@Slf4j
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminRepository adminRepository;
    @Autowired
    IdWorker idWorker;
    @Autowired
    HttpServletRequest request;
    @Autowired
    JwtUtil jwtUtil;

    /**
     * 加解密
     */
    @Autowired
    private BCryptPasswordEncoder encoder;

    /**
     * 使用SpringSecurity的BCryptPasswordEncoder进行加密
     *
     * @param admin
     */
    @Override
    public void addAdmin(Admin admin) {
        admin.setId(idWorker.nextId() + "");
        //密码加密
        admin.setPassword(encoder.encode(admin.getPassword()));
        adminRepository.save(admin);
    }

    @Override
    public Admin login(Admin admin) {
        //先根据用户名查询对象。
        Admin adminLogin = adminRepository.findByLoginname(admin.getLoginname());
        //然后拿数据库中的密码和用户输入的密码匹配是否相同。
        if (adminLogin != null && encoder.matches(admin.getPassword(), adminLogin.getPassword())) {
            //保证数据库中的对象中的密码和用户输入的密码是一致的。登录成功
            return adminLogin;
        }
        //登录失败
        return null;
    }

    /**
     * 删除 必须有admin角色才能删除
     */
    @Override
    public ResultObject deleteById(String id) {
        String authorization = request.getHeader("Authorization");
        if (authorization == null) {
            return new ResultObject(false, StatusCode.ACCESSERROR, "权限不足,没有授权");
        } else {
            if (!authorization.startsWith("Bearer")) {
                return new ResultObject(false, StatusCode.ACCESSERROR, "权限不足,错误的Token");
            } else {
                //提取token
                String token = authorization.substring(7);
                Claims claims = null;
                try{
                     claims = jwtUtil.parseJWT(token);
                }catch (MalformedJwtException e){
                    return new ResultObject(false, StatusCode.ACCESSERROR, "权限不足,Token解析错误");
                }
                log.info("claims:"+claims);
                if (claims == null) {
                    return new ResultObject(false, StatusCode.ACCESSERROR, "权限不足,Token解析为空");
                } else {
                    if ((!"admin".equals(claims.get("roles")))) {
                        return new ResultObject(false, StatusCode.ACCESSERROR, "权限不足,不是管理员角色");
                    }else {
                        adminRepository.deleteById(id);
                        return new ResultObject(false, StatusCode.ACCESSERROR, "删除成功");
                    }
                }
            }
        }
    }
}
//Authorization:Bearer eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxNjUwOTI0ODAyMzUyMTI4MDAiLCJzdWIiOiJhZG1pbiIsImlhdCI6MTYwNDM5MDg3Miwicm9sZXMiOiJhZG1pbiIsInBlcm1pc3Npb24iOiJjcnVkIiwiZXhwIjoxNjA0NDc3MjcyfQ.0lb02-5QzRNBCns5ZDoA8duXQQ45jgNILjRud5sdVHo